package com.itdct.onflow.generator.template

import com.itdct.onflow.core.entity.BaseUserEntity
import com.itdct.onflow.generator.base.BaseTemplate
import com.itdct.onflow.generator.config.GeneratorConfig
import com.itdct.onflow.generator.constant.GroupEnum
import com.itdct.onflow.generator.model.ClassModel
import com.itdct.onflow.generator.model.CompareResultModel
import com.itdct.onflow.generator.model.FieldModel

/**
 * @author Zhouwx
 * @date 2025/8/11 16:45:17
 * @version 1.0
 * @description
 */
open class ListVoTemplate(classModel: ClassModel, generatorConfig: GeneratorConfig) : BaseTemplate(classModel, generatorConfig) {
    init {
        filterFieldList.add("id")
        filterFieldList.add("del")
        filterFieldList.add("version")
        filterFieldList.add("deleteUser")
        filterFieldList.add("deleteTime")
    }

    override fun render(): String {
        return """
${uuidPrint()}
package ${classModel.packageName}.vo

import com.itdct.onflow.core.vo.BaseListVo
import io.swagger.v3.oas.annotations.media.Schema
import java.util.*${extraImports()}

/**
 * @author ${generatorConfig.authorName}
 * @date ${getDateString()}
 * @version 1.0
 * @description ${classModel.classUsage}列表返回值
 */
@Schema(name = "${classModel.classUsage}列表返回值", description = "${classModel.classUsage}列表返回值")
class ${classModel.className}ListVo : BaseListVo() {
${rangeStart("fields")}
${setFields()}
${rangeEnd("fields")}${createUpdateUserField()}
}
""".trimIndent()
    }

    fun createUpdateUserField(): String {
        val clazz = classModel.clazz ?: return ""
        if (BaseUserEntity::class.java.isAssignableFrom(clazz)) {
            return "\n\n" + """
    @Schema(title = "创建人名称", example = "")
    var createUserName = ""

    @Schema(title = "创建人名称", example = "")
    var updateUserName = ""
            """.trimMargin()
        }
        return ""
    }

    override fun onModify(compareResultModel: CompareResultModel, content: String): String {
        var content = content
        val addFields = compareResultModel.addFields
        val addIndex = content.indexOf(rangeEnd("fields"))
        content = insertFieldListContent(content, addFields, addIndex, { index, fieldModel -> fieldContent(fieldModel) })

        val delFields = compareResultModel.delFields
        content = deleteRangeFunctionCode(content, "fields", delFields, { fieldModel -> fieldContent(fieldModel) })

        val modifyPairs = compareResultModel.modifyPairs
        content = modifyReplace(content, "fields", modifyPairs, { fieldModel -> fieldContent(fieldModel) })
        return content
    }

    fun setFields(): String {
        return fieldsGen("", { i, fieldModel ->
            fieldContent(fieldModel)

        })
    }

    private fun fieldContent(fieldModel: FieldModel) = """
    |    @Schema(title = "${fieldModel.comment}", example = "")${dict(fieldModel)}
    |    var ${fieldModel.name}: ${typeName(fieldModel)}? = null
    |${additionField(fieldModel)}
                """.trimMargin()

    private fun typeName(fieldModel: FieldModel): String {
        if (fieldModel.dictCode.isBlank()) {
            return fieldModel.typeName
        }

        // INFO: Zhouwx: 2025/9/22 如果该值存在字典信息，且返回为Int或者Long的情况下要改为String，因为code返回的值肯定是String，不这么搞前端回显会有问题
        val kClass = fieldModel.kClass
        if (kClass == Int::class || kClass == Long::class) {
            return "String"
        } else {
            return fieldModel.typeName
        }
    }

    fun dict(fieldModel: FieldModel): String {
        return if (fieldModel.dictCode.isNotBlank()) {
            """|
|    @Dict(code = "${fieldModel.dictCode}", field = "${fieldModel.name}${fieldModel.dictGenSuffix}")
            """.trimMargin()
        } else {
            ""
        }
    }

    fun additionField(fieldModel: FieldModel): String {
        val stringBuilder = StringBuilder()
        if (fieldModel.dictCode.isNotBlank()) {
            // INFO: Zhouwx: 2025/8/12 字典相关添加字典值
            stringBuilder.append(
                """|
|    @Schema(title = "${fieldModel.comment}字典映射值", example = "")
|    var ${fieldModel.name}${fieldModel.dictGenSuffix}: String? = null
|    
            """.trimMargin()
            )
        }

        if (fieldModel.targetClass != null) {
            stringBuilder.append(
                """|
|    @Schema(title = "${fieldModel.comment}对应值", example = "")
|    var ${fieldModel.name}${fieldModel.idGenSuffix}: String? = null
|    
            """.trimMargin()
            )
        }
        return stringBuilder.toString()
    }

    fun extraImports(): String {
        val stringBuilder = StringBuilder()
        classModel.fieldList.any {
            it.typeName == "BigDecimal"
        }.also {
            if (it) {
                stringBuilder.append("\nimport java.math.BigDecimal")
            }
        }

        classModel.fieldList.any {
            it.dictCode.isNotBlank()
        }.also {
            if (it) {
                stringBuilder.append("\nimport com.itdct.onflow.core.annotation.Dict")
            }
        }

        return stringBuilder.toString()
    }

    override fun belongGroup(): GroupEnum {
        return GroupEnum.BACKEND
    }

    override fun subModuleName(): String {
        return "adaptor"
    }

    override fun getFolderFileName(): String {
        return "vo/${classModel.className}ListVo.kt"
    }

}